import 'dart:convert';

import 'package:flutter_deer/generated/json/base/json_field.dart';
import 'package:flutter_deer/generated/json/get_mqtt_info_entity.g.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:sp_util/sp_util.dart';

export 'package:flutter_deer/generated/json/get_mqtt_info_entity.g.dart';

@JsonSerializable()
class GetMqttInfoEntity {
	int? isSuperuser = 0;
	GetMqttInfoMqttInfo? mqttInfo;
	String? password = '';
	String? username = '';

	GetMqttInfoEntity();

	factory GetMqttInfoEntity.fromJson(Map<String, dynamic> json) => $GetMqttInfoEntityFromJson(json);

	Map<String, dynamic> toJson() => $GetMqttInfoEntityToJson(this);

	@override
	String toString() {
		return jsonEncode(this);
	}

	// 存储
	void save() {
		SpUtil.putObject(Constant.mqttInfo, toJson());
	}

	// 读取
	static GetMqttInfoEntity? get() {
		final String? jsonString = SpUtil.getString(Constant.mqttInfo);
		if (jsonString?.isNotEmpty!= true) {
			return null;
		}

		try {
			final dynamic data = json.decode(jsonString!);
			if (data is Map<String, dynamic>) {
				return GetMqttInfoEntity.fromJson(data);
			} else {
				print('解析失败：期望 Map<String, dynamic>，但返回的是 ${data.runtimeType}');
				return null;
			}
		} catch (e, stackTrace) {
			print('JSON 解析失败: $e\n$stackTrace');
			return null;
		}
	}
}

@JsonSerializable()
class GetMqttInfoMqttInfo {
	String? host = '';
	int? port = 0;
	String? protocol = '';
	String? pullInterval = '';
	String? receipt = '';
	List<String>? subscribes = [];

	GetMqttInfoMqttInfo();

	factory GetMqttInfoMqttInfo.fromJson(Map<String, dynamic> json) => $GetMqttInfoMqttInfoFromJson(json);

	Map<String, dynamic> toJson() => $GetMqttInfoMqttInfoToJson(this);

	@override
	String toString() {
		return jsonEncode(this);
	}
}